import axios from "axios";
import router from "../router";

const http = axios.create({
  baseURL: "https://v3pz.itndedu.com/v3pz",
  timeout: 5000,
  headers:{
    "terminal": "h5"
  }
});

// 请求拦截器
http.interceptors.request.use((config) => {
  // 在发送请求之前做些什么
  const token = localStorage.getItem("h5_token");
  const whiteList = ['/login'];
  if (token && !whiteList.includes(config.url)) {
    config.headers['h-token'] = token;
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 响应拦截器
http.interceptors.response.use((response) => {
  // 对响应数据做点什么
  if (response.data.code === -1) {
    console.log(response.data.msg);
  }
  if (response.data.code === -2) {
    localStorage.removeItem('h5_token');
    localStorage.removeItem('h5_userInfo');
    console.log('登录已过期，请重新登录');
    router.push('/login');
  }
  return response;
}, (error) => {
  // 对响应错误做点什么
  console.log(error);
  console.log('网络错误，请稍后重试');
  return Promise.reject(error);
});

export default http;